import { parseParams } from './utils'

interface IOptions {
	url: string
	method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
	data?: any
	isForm?: boolean
	body?: any
    headers?: any
}
const defaultOptions = {
    credentials: 'include',
    headers: {
        "Accept": 'application/json'
    },
    data: {},
    isForm: false,
}

export default async function fetch(options: IOptions) {
    options = {
        ...defaultOptions,
        ...options,
    }
    let url = options.url
    delete options.url
    options.method = options.method || 'GET'
    if (options.method === 'GET') {
        url = parseParams(url, options.data)
    } else {
        if (options.isForm) {
            let formDate = new FormData()
            for (let key in options.data) {
                formDate.append(key, options.data[key])
            }
            options.body = formDate
        } else {
            options.headers = {
                Accept: 'application/json',
                'Content-Type': 'application/json;  charset=utf-8'
            }
            options.body = JSON.stringify(options.data)
        }
    }
    try {
        const response = await window.fetch(url, options)
        const data = await response.json()
        if (response.ok) {
            return data
        }
    } catch (error) {
        throw error
    }
}